package org.example;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.PriorityOrdered;

/**
 * @author void
 * @date 2021/10/15 15:06
 * @desc 自定义切面
 */
@Aspect
@EnableAspectJAutoProxy(exposeProxy = true, proxyTargetClass = true)
@Configuration
@ConditionalOnProperty(prefix = "aspect.log", name = "enable", havingValue = "true", matchIfMissing = true)
public class AspectLogAutoConfiguration implements PriorityOrdered {

    protected Logger logger = LoggerFactory.getLogger(getClass());
    
    @Around("@annotation(org.example.AspectLog)")
    public Object isOpen(ProceedingJoinPoint thisJoinPoint) throws Throwable {
        String taskName = thisJoinPoint.getSignature().toString().substring(
                thisJoinPoint.getSignature().toString().indexOf(" "),
                thisJoinPoint.getSignature().toString().indexOf("(")
        );
        taskName = taskName.trim();
        long time = System.currentTimeMillis();
        Object result = thisJoinPoint.proceed();
        logger.info("method:{} run:{}ms", taskName, System.currentTimeMillis()-time);
        return result;
    }
    
    @Override
    public int getOrder() {
        return Integer.MAX_VALUE;
    }
}
